<template>
  <div ref="tableData">
    <div v-if="printerTitle">
      <div style="font-size: 40px; font-weight: bold; text-align: center; padding-bottom: 30px; padding-top: 30px;">
        {{ this.$route.query.routerName }}
      </div>
    </div>
    <a-table id="tableData" bordered :loading="tableLoading"
             :pagination="false"
             :scroll="{ y: tableHeight }"
             :rowKey="(record, index) => { return index }"
             :columns="columnBox" :data-source="tableData" size="small">
      <!--      自定义插槽-->
      <template slot="link" slot-scope="text, record, index, column">
        <a @click="openVisible(record, column)">{{ text }}</a>
      </template>
      <template slot="fixedNum" slot-scope="text, record, index, column">
        {{ parseFloat(text).toFixed(column.fixedNum) }}
      </template>
      <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
      >
        <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`请输入${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          查询
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
          重置
        </a-button>
      </div>
      <a-icon
          slot="filterIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
      />
      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
              v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
                v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                :key="i"
                class="highlight"
            >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>
    </a-table>
    <!--    分页用时解开-->
    <!--    <a-pagination-->
    <!--        v-if="tableData.length"-->
    <!--        show-size-changer-->
    <!--        @showSizeChange="onShowSizeChange"-->
    <!--        :page-size-options="pageSizeOptions"-->
    <!--        v-model="currentPage"-->
    <!--        style="float: right; margin-bottom: 20px; margin-top: 20px;"-->
    <!--        :total="totalTable"-->
    <!--        :show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"-->
    <!--        :page-size="pagesize"-->
    <!--        :default-current="1"-->
    <!--        @change="onChange"-->
    <!--    >-->
    <!--    </a-pagination>-->

    <!--    <div v-for="(item, index) in columnBox" :key="index">-->
    <!--      {{ item }}-->
    <!--    </div>-->
    <!--    钻取抽屉-->
    <a-drawer
        title="数据列表"
        placement="top"
        :visible="visible"
        height="85%"
        :maskClosable="true"
        :keyboard="true"
        @close="closeVisible"
    >
      <iframe :src="iframeSrc" width="100%" height="100%" frameborder="0"></iframe>
    </a-drawer>
  </div>
</template>

<script>
import axios from "axios";
import ExportExcel from "@/assets/js/export";
// import ExportExcelTitle from "@/assets/js/exportTitle";
import ExportExcelFormat from "@/assets/js/exportFormat";
import _ from "lodash"; // 导出获取表单

export default {
  name: "Table",
  props: {
    projectId: {
      type: String, default: () => {
      }
    },
    queryId: {
      type: String, default: () => {
      }
    },
    fillName: {
      type: String, default: () => {
      }
    },
    conditions: {
      type: Object, default: () => {
      }
    },
    tableHeight: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      visible: false,
      iframeSrc: "",
      searchInput: null,
      searchText: '',
      searchedColumn: '',
      printerTitle: false,
      currentPage: 1,
      pagesize: 20,
      totalTable: 1000,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      fieldList: {
        type: Array,
        default: () => []
      },
      tableLoading: false,
      tableData: [],
      columnBox: [],
      myPagination: {
        defaultPageSize: 20
      },
      dataExcel: [] // 导出excel数据
    };
  },
  // 监听路由发生变化时刷新信息
  watch: {
    $route(to, from) {
      this.fieldList = [];
      this.tableData = [];
      this.columnBox = [];
      this.loadTableHeader();
    }
  },
  mounted() {
    this.loadTableHeader();
  },
  methods: {
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },

    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    // 获取查询条件
    loadTableHeader() {
      axios
          .get("/api/" +
              this.projectId + "/" + this.queryId + "/" + this.fillName + "/getTableFields"
          )
          .then(resp => {
            if (resp.data.code == "500") {
              console.log(resp.data.data);
            } else {
              this.fieldList = resp.data.data;
              const columnBox = resp.data.data;
              for (let i = 0; i < columnBox.length; i++) {
                // 合并数据单元格配置
                if (columnBox[i].merge) {
                  columnBox[i].customRender = (text, row, index) => {
                    const obj = {
                      children: text,
                      attrs: {}
                    }
                    const data = this.tableData;
                    obj.attrs.rowSpan = this.getRowSpanCount(data || [], columnBox[i].mergeName, index)
                    return obj
                  }
                }
                // 筛选配置
                if (columnBox[i].filter) {
                  columnBox[i].scopedSlots = {
                    filterDropdown: 'filterDropdown',
                    filterIcon: 'filterIcon',
                    customRender: 'customRender',
                  }
                  columnBox[i].onFilter = (value, record) =>
                      record[columnBox[i].dataIndex]
                          .toString()
                          .toLowerCase()
                          .includes(value.toLowerCase());
                  columnBox[i].onFilterDropdownVisibleChange = visible => {
                    if (visible) {
                      setTimeout(() => {
                        this.searchInput.focus();
                      });
                    }
                  }
                }
                // 排序配置
                if (columnBox[i].sortable) {
                  columnBox[i].sorter = (a, b) => a[columnBox[i].dataIndex] - b[columnBox[i].dataIndex];
                }
                // 钻取配置
                if (columnBox[i].link) {
                  columnBox[i].scopedSlots = {
                    customRender: 'link'
                  }
                }
                // 渲染显示数据四舍五入
                if (columnBox[i].fixedNum) {
                  columnBox[i].scopedSlots = {
                    customRender: 'fixedNum'
                  }
                }
              }
              this.columnBox = columnBox;
            }
          });
    },
    /*
     * 合并列
     */
    getRowSpanCount(data, key, target) {
      if (!Array.isArray(data)) return 1;
      data = data.map(_ => _[key]); // 只取出筛选项
      let preValue = data[0];
      const res = [[preValue]]; // 放进二维数组里
      let index = 0; // 二维数组下标
      for (let i = 1; i < data.length; i++) {
        if (data[i] === preValue) { // 相同放进二维数组
          res[index].push(data[i]);
        } else { // 不相同二维数组下标+1
          index += 1;
          res[index] = [];
          res[index].push(data[i]);
          preValue = data[i];
        }
      }
      const arr = [];
      res.forEach((_) => {
        const len = _.length;
        for (let i = 0; i < len; i++) {
          arr.push(i === 0 ? len : 0);
        }
      });
      return arr[target];
    },
    // 表格查询
    loadData(callback, pages) {
      let conditionsBox = JSON.parse(JSON.stringify(this.conditions));
      // 获取分页总条数
      this.tableLoading = true;
      // 分页处理
      if (!pages) {
        this.$set(conditionsBox, 'pagenumber', 1);
        this.currentPage = 1;
        this.$set(conditionsBox, 'pagesize', this.pagesize);
      } else {
        this.$set(conditionsBox, 'pagenumber', this.currentPage);
        this.$set(conditionsBox, 'pagesize', this.pagesize);
      }
      // 向后台请求数据，并加载查询结果
      this.loadTableHeader();
      this.tableData = [];
      axios
          .post("/api/" +
              this.projectId + "/" + this.queryId + "/" + this.fillName + "/execute",
              conditionsBox
          )
          .then(resp => {
            if (!pages) {
              callback();
            }
            if (resp.data.code == "500") {
              console.log(resp.data.data);
            } else {
              this.tableData = resp.data.data;
              this.totalTable = resp.data.totalcount; // 分页
              if (this.tableData.length) {
                let data = JSON.parse(JSON.stringify(this.tableData[0]));
                this.tableData.push(data);
                for (let i = 0; i < this.columnBox.length; i++) {
                  // 合计配置
                  if (this.columnBox[i].sumed) {
                    let sum = 0;
                    for (let j = 0; j < this.tableData.length; j++) {
                      if (j !== this.tableData.length - 1) {
                        sum += parseFloat(this.tableData[j][this.columnBox[i].dataIndex]);
                      }
                    }
                    this.tableData[this.tableData.length - 1][this.columnBox[i].dataIndex] = sum.toFixed(2);
                  } else {
                    this.tableData[this.tableData.length - 1][this.columnBox[i].dataIndex] = '';
                  }
                  if (i === 0) {
                    this.tableData[this.tableData.length - 1][this.columnBox[i].dataIndex] = '合计';
                  }
                }
              }
              this.tableLoading = false;
            }
          });
    },
    // 分页
    onChange(page) {
      this.currentPage = page;
      this.loadData('', true);
    },
    onShowSizeChange(current, pageSize) {
      this.pagesize = pageSize;
      this.currentPage = current;
      this.loadData('', true);
    },
    // 时间戳转换字符串
    formatDate(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    dataToExcel(fileName) {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      ExportExcel(this.columnBox, this.dataExcel, fileName);
    },
    dataToExcelFormat(fileName) {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      ExportExcelFormat(this.columnBox, this.dataExcel, fileName);
      // ExportExcelTitle(this.columnBox, this.dataExcel, y + '' + MM + '' + '' + d + this.$route.query.routerName, this.$route.query.routerName, this.projectId, this.conditions);
    },
    printer() {
      this.printerTitle = true;
      this.$nextTick(() => {
        this.$print(this.$refs.tableData, {'noPrint': '.ant-pagination'});
        this.printerTitle = false;
      });
    },
    // 打开钻取遮罩层
    openVisible(record, column) {
      console.log('地址', column.link);
      console.log('参数', record);
      const query = Object.keys(record).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(record[key])}`).join('&');
      this.iframeSrc = '/#/query/' + this.projectId + "/" + this.queryId + '/' + column.link + '?' + query;
      this.visible = true;
    },
    // 关闭钻取遮罩层
    closeVisible() {
      this.iframeSrc = '';
      this.visible = false;
    }
  }
};
</script>

<style scoped>
.el-table {
  overflow: visible !important;
}

/deep/ th {
  background-color: #ffffff !important;
  color: #909399 !important;
  font-weight: bold !important;
}

/deep/ .diffRow {
  background-color: #C9DAF8;
}

/deep/ .diffRowTop {
  background-color: #C9DAF8;
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 999;
}

/deep/ .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  padding-bottom: 0px !important;
  margin-bottom: -16px !important;
  margin-right: -16px !important;
}

/deep/ .ant-drawer-body {
  height: calc(100% - 61px);
  padding-top: 0;
  padding-bottom: 0;
}
</style>
